package config;

import gms.ILookupTable;
import gms.IPartition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Catalog {
	private static Logger logger = LoggerFactory.getLogger(Catalog.class);
	
	private Map<String, DBMetaData> DBMetaDataMap = new HashMap<String, DBMetaData>();
	private static Catalog instance = new Catalog();
	
	public static Catalog getInstance() {
		return instance;
	}
	
	private Catalog() {
		
	}
	
	public void init() {
		DBOption[] dbs = Configure.getDBOptions();
		try {
			for (DBOption db : dbs) {
				DBMetaData metaData = new DBMetaData();
				metaData.setDbName(db.dbname);
				metaData.setLookupTable((ILookupTable) Class.forName(db.lookuptableclass).newInstance());
				metaData.setPartition((IPartition) Class.forName(db.partitionclass).newInstance());
				DBMetaDataMap.put(metaData.getDbName(), metaData);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new RuntimeException();
		} 
	}
	
	public DBMetaData getDBMetaData(String db) {
		return DBMetaDataMap.get(db);
	}
	
	public IPartition getDBPartition(String db) {
		DBMetaData meta = DBMetaDataMap.get(db); 
		if (meta != null)
			return meta.getPartition();
		else
			return null;
	}
	
	public ILookupTable getLookupTable(String db) {
		DBMetaData meta = DBMetaDataMap.get(db); 
		if (meta != null)
			return meta.getLookupTable();
		else
			return null;
	}
	
	public List<DBMetaData> ListDb() {
		return new ArrayList<DBMetaData>(DBMetaDataMap.values());
	}
}
